#include "ZYM568.h"
#include "device.h"

#define VHW_IIC_ZYM568 vIIC_4

#define ZYM568_ADDR 0x0C
#define ZYM568_SINGLE_MEASUREMENT_MODE 0x3E
#define ZYM568_BURST_MODE 0x1E
#define ZYM568_READ_MEASUREMENT 0x4E
#define ZYM568_LOW_POWER_MODE 0x80

unsigned short ZYM568_SETTIM = 0;

static unsigned char zym568_read(unsigned char reg, unsigned char *data, unsigned char len)
{
	if (Device_Write(VHW_IIC_ZYM568, &reg, 1, ZYM568_ADDR) == 0)
	{
		return (Device_Read(VHW_IIC_ZYM568, data, len, ZYM568_ADDR) == 0) ? 1 : 0;
	}
	return 0;
}

// static unsigned char zym568_write(unsigned char reg, unsigned char *data, unsigned char len)
// {
// 	unsigned char buffer[20] = {reg};

// 	memcpy(&buffer[1], data, len);
// 	return (Device_Write(VHW_IIC_ZYM568, buffer, len + 1, ZYM568_ADDR) == 0) ? 1 : 0;
// }

/***************************************************************************
磁场计进行一次转换
return:0失败，1成功
***************************************************************************/
unsigned char ZYM568_setMode(void)
{
	unsigned char flag = 0x00;
	if (zym568_read(ZYM568_SINGLE_MEASUREMENT_MODE, &flag, 1) == 0)
		return 0;
	if (!(flag & 0x20))
		return 0;
	else
		return 1;
}

/***************************************************************************
磁场计读取数据
return:0失败，1成功
***************************************************************************/
unsigned char ZYM568_init(void)
{
	unsigned char flag = 0x00;
	if (zym568_read(0x3E, &flag, 1) == 0)
		return 0;
	else
	{
		ZYM568_SETTIM = 0;
		return 1;
	}
}

/***************************************************************************
磁场计进入低功耗模式
return:0失败，1成功
***************************************************************************/
unsigned char ZYM568_lowpowermode(void)
{
	unsigned char flag = 0x00;
	// ZYM568_SETTIM = 0;
	if (zym568_read(ZYM568_LOW_POWER_MODE, &flag, 1) == 0)
		return 0;
	if (!(flag & 0x10))
		return 0;
	else
		return 1;
}

/***************************************************************************
磁场计读取数据,
short mag[3]:更新的磁场缓存
short dtim:调用本函数的时间差，单位ms
return:0数据没有更新，1数据更新成功
***************************************************************************/
unsigned char ZYM568_Get_Data(short mag[3], short dtim)
{
	unsigned char buffer[7];

	if (ZYM568_SETTIM == 0)
	{
		ZYM568_SETTIM++;
		ZYM568_setMode();
		return 0;
	}
	else
	{
		ZYM568_SETTIM += dtim;
		if (ZYM568_SETTIM > 16) // 每次读取数据最少间隔24ms
		{
			ZYM568_SETTIM = 1;
			if (zym568_read(ZYM568_READ_MEASUREMENT, buffer, 7) == 0)
				return 0;
			mag[0] = (buffer[1] << 8) | buffer[2];
			mag[1] = (buffer[3] << 8) | buffer[4];
			mag[2] = (buffer[5] << 8) | buffer[6];
			if (ZYM568_setMode() == 0)
				return 0;
			else
				return 1;
		}
		return 0;
	}
}
